package com.lambkit.plugin.sqlite;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.lambkit.core.LifecycleException;
import com.lambkit.core.plugin.Plugin;
import com.lambkit.db.DbPool;
import com.lambkit.db.hutool.HutoolDb;

import static cn.hutool.db.dialect.DriverNamePool.DRIVER_SQLLITE3;

/**
 * @author yangyong(孤竹行)
 */
public class SqlitePlugin extends Plugin {

    private String dbfile;
    private String username;
    private String password;
    private String name = DbPool.DEFAULT_NAME;

    public SqlitePlugin(String dbfile) {
        this.dbfile = dbfile;
    }

    public SqlitePlugin(String dbfile, String username, String password)  {
        this.dbfile = dbfile;
        this.username = username;
        this.password = password;
    }

    public SqlitePlugin(String name, String dbfile, String username, String password)  {
        this.dbfile = dbfile;
        this.username = username;
        this.password = password;
        this.name = name;
    }

    public SqlitePlugin(SqliteConfig config) {
        this.dbfile = config.getUrl();
        this.username = config.getUsername();
        this.password = config.getPassword();
        this.name = config.getName();
    }

    @Override
    public void start() throws LifecycleException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:sqlite:" + dbfile);
        if(StrUtil.isNotBlank(username) && StrUtil.isNotBlank(password))  {
            dataSource.setUsername(username);
            dataSource.setPassword(password);
        }
        HutoolDb htDb = new HutoolDb(dataSource, DRIVER_SQLLITE3);
        DbPool.add(name, htDb);
    }

    @Override
    public void stop() throws LifecycleException {
        super.stop();
        DbPool.remove(name);
    }
}
